<template>
  <div>
    <div class="mask" v-show="isShowSelect" @click="isShowSelect = !isShowSelect"></div>
    <el-popover placement="bottom-start" :width="width" trigger="manual"
                v-model="isShowSelect" @hide="popoverHide">
      <el-tree class="common-tree" :style="style" ref="tree" :data="data" :props="treeProps"
               :show-checkbox="multiple"
               :node-key="nodeKey"
               :check-strictly="checkStrictly"
               :default-expand-all="defaultExpandAll"
               :expand-on-click-node="false"
               :highlight-current="true"
               @node-click="handleNodeClick"
      ></el-tree>
      <div style="text-align: right; margin: 0" v-if="multiple">
        <el-button size="mini" type="text" @click="isShowSelect = false">取消</el-button>
        <el-button type="primary" size="mini" @click="handleCheckChange">确定</el-button>
      </div>
      <el-select :style="selectStyle" slot="reference"
                 ref="select"
                 :size="size"
                 :placeholder="placeholder"
                 v-model="selectedData"
                 :multiple="multiple"
                 @click.native="isShowSelect = !isShowSelect"
                 class="tree-select">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
    </el-popover>
  </div>
</template>

<script>
export default {
  name: "el-tree-select",
  props: {
    // 树结构数据
    placeholder: {
      type: String,
      default: null,
    },
    defaultExpandAll: {
      type: Boolean,
      default: false
    },
    data: {
      type: Array,
      default() {
        return [];
      }
    },
    treeProps: {
      type: Object,
      default() {
        return {};
      }
    },
    // 配置是否可多选
    multiple: {
      type: Boolean,
      default() {
        return false;
      }
    },
    nodeKey: {
      type: String,
      default() {
        return 'id';
      }
    },
    // 显示复选框情况下，是否严格遵循父子不互相关联
    checkStrictly: {
      type: Boolean,
      default() {
        return false;
      }
    },
    // 默认选中的节点key数组
    checkedKeys: {
      type: Array,
      default() {
        return [];
      }
    },
    size: {
      type: String,
      default() {
        return 'small';
      }
    },
    width: {
      type: Number,
      default() {
        return 250;
      }
    },
    height: {
      type: Number,
      default() {
        return 300;
      }
    }
  },
  watch: {
    data: function (val) {
      if (!val) return
      this.loadDataState = true;
      this.$nextTick(() => this.initCheckedData())
    },
    isShowSelect(val) {
      // 隐藏select自带的下拉框
      this.$refs.select.blur();
    },
    checkedKeys: {
      handler: function (val) {
        this.checkedKeys = val;
        this.initCheckedData();
      },
      deep: true
    }
  },
  data() {
    return {
      isShowSelect: false, // 是否显示树状选择器
      options: [],
      selectedData: [], // 选中的节点
      style: 'width:' + this.width + 'px;' + 'height:' + this.height + 'px;',
      selectStyle: 'width:' + (this.width + 24) + 'px;',
      checkedIds: [],
      checkedData: [],
      loadDataState: false,
    }

  },

  mounted() {
    this.initCheckedData();
  },
  methods: {
    initCheckedData() {
      if (!this.loadDataState) return;
      if (this.multiple) {
        if (this.checkedKeys.length > 0) {
          // 勾选上传进来的节点
          this.$refs.tree.setCheckedKeys(this.checkedKeys);
        } else {
          // 清空所有勾选
          let checkedKeys = this.$refs.tree.getCheckedKeys(); // 所有被选中的节点的 key 所组成的数组数据
          for (let i = 0; i < checkedKeys.length; i++) {
            this.$refs.tree.setChecked(checkedKeys[i], false);
          }
        }
      } else {
        if (this.checkedKeys.length > 0) {
          // 选中传进来的节点
          let item = this.checkedKeys[0];
          this.$refs.tree.setCurrentKey(item);
          let node = this.$refs.tree.getNode(item);
          if (!node) return
          this.selectedData = node.label;
        } else {
          // 清空选中
          this.selectedData = '';
          this.$refs.tree.setCurrentKey(null);
        }
      }
    },
    popoverHide() {
      if (this.multiple) {
        this.checkedIds = this.$refs.tree.getCheckedKeys(); // 所有被选中的节点的 key 所组成的数组数据
        this.checkedData = this.$refs.tree.getCheckedNodes(); // 所有被选中的节点所组成的数组数据
      } else {
        this.checkedIds = this.$refs.tree.getCurrentKey();
        this.checkedData = this.$refs.tree.getCurrentNode();
      }
      this.$emit('popoverHide', this.checkedIds, this.checkedData);
    },
    // 节点被点击时的回调,返回被点击的节点数据
    handleNodeClick(data, node) {
      if (!this.multiple) {
        let tmpMap = {};
        tmpMap.value = node.key;
        tmpMap.label = node.label;
        this.options = [];
        this.options.push(tmpMap);
        this.selectedData = node.label;
        this.isShowSelect = !this.isShowSelect;
        this.$emit("nodeClickChange", node.key, node.data, node)
      }
    },
    // 节点选中状态发生变化时的回调
    handleCheckChange() {
      let checkedKeys = this.$refs.tree.getCheckedKeys(); // 所有被选中的节点的 key 所组成的数组数据
      this.options = checkedKeys.map((item) => {
        let node = this.$refs.tree.getNode(item); // 所有被选中的节点对应的node
        let tmpMap = {};
        tmpMap.value = node.key;
        tmpMap.label = node.label;
        return tmpMap;
      });
      this.selectedData = this.options.map((item) => {
        return item.label;
      });
      let nodes = this.$refs.tree.getCheckedNodes();
      this.isShowSelect = false;
      this.$emit("onCheckedChange", checkedKeys, nodes)

    }
  },
}
</script>

<style scoped>
.mask {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  opacity: 0;
}

.common-tree {
  overflow: auto;
}
</style>

<style>
.tree-select .el-select__tags .el-tag .el-tag__close {
  display: none;
}

.tree-select .el-select__tags .el-tag .el-icon-close {
  display: none;
}
</style>
